import sha256 from 'crypto-js/sha256'

// 区块
export class Block{
    constructor(data,prevHash){
        this.data = data;
        this.prevHash = prevHash;
        this.hash = this.computeHash();
    }
    computeHash(){
        return sha256(this.data + this.prevHash).toString();
    }

}

// 链
export class Chain{
    constructor(){
        this.chain = [this.rootBlock()];
    }
    
    getLatestBlock(){
        return this.chain[this.chain.length-1];
    }
    
    rootBlock(){
        const rootBlock = new Block('root','')
        return rootBlock;
    }
    
    //添加区块到区块链
    addBlockToChain(newBlock){
        newBlock.prevHash = this.getLatestBlock().hash;
        newBlock.hash = newBlock.computeHash();
        this.chain.push(newBlock);
    }

    //验证区块链
    validateChain(){
        if(this.chain.length === 1){
            if(this.chain[0].hash !== this.chain[0].computeHash()){
                return false;
            }
            return true;
        }

        for(let i = 1; i<= this.chain.length-1; i++){
            const blockToValidate = this.chain[i];
            //当前数据有没有改变
            if(blockToValidate.hash !== blockToValidate.computeHash()){
                return false;
            }
            //验证区块的prevHash 是否等于 previous区块的hash
            const prevBlock = this.chain[i-1];
            if(blockToValidate.prevHash !== prevBlock.hash){
                return false;
            }            
        }
        return true;
    }
}
